#!/bin/bash
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
COMMON_SHELL="$SCRIPT_DIR/../common.sh" 
SFTP_TOOL="$SCRIPT_DIR/../tools/sftp"

if [ ! -f "$COMMON_SHELL" ]; then
    if [ ! -f ./common.sh ]; then
        wget https://gitee.com/anolis/hygon-devkit/raw/master/common.sh
        chmod +x common.sh
    fi
    source ./common.sh
else
    source $COMMON_SHELL
fi

PKG_SUFFIX=$(get_os_info | sed -n '1p')

# Check if the correct number of arguments is provided
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 <version>"
    exit 1
fi

# Get the file name at remote path
REMOTE_PATH=/hygon-devkit/4.0/2025-01-01/alloc-libs

if [ ! -f "$SFTP_TOOL" ]; then
    if [ ! -f ./sftp ]; then
        wget https://gitee.com/anolis/hygon-devkit/raw/master/tools/sftp
    fi
    chmod +x sftp
    FILE_NAME=$(./sftp list "$REMOTE_PATH" |  grep -oP "libhtcmalloc[-_]$1[-_][0-9]+[._][^.]+\.$PKG_SUFFIX$" | awk '{print $1}')
    ./sftp download "$REMOTE_PATH"/$FILE_NAME $SCRIPT_DIR/$FILE_NAME
else
    FILE_NAME=$("$SFTP_TOOL" list "$REMOTE_PATH" |  grep -oP "libhtcmalloc[-_]$1[-_][0-9]+[._][^.]+\.$PKG_SUFFIX$" | awk '{print $1}')
    "$SFTP_TOOL" download "$REMOTE_PATH"/$FILE_NAME $SCRIPT_DIR/$FILE_NAME
fi
if [ $? -ne 0 ]; then
    echo "Download failed"
    exit 1
fi

if [ "$PKG_SUFFIX" == "deb" ]; then
    dpkg -i $SCRIPT_DIR/$FILE_NAME
else
    rpm -ivh --replacefiles $SCRIPT_DIR/$FILE_NAME
fi